package com.moduleSys.userService;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.moduleSys.entity.system.Role;
import com.moduleSys.entity.system.User;
import com.moduleSys.entity.system.UserRole;
import com.moduleSys.mapper.RoleMapper;
import com.moduleSys.mapper.UserMapper;
import com.moduleSys.mapper.UserRoleMapper;
import com.moduleSys.userService.UserService;
import com.moduleSys.utils.json.JsonResult;
import com.moduleSys.utils.string.GenerateRandomNumber;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by czw on 2017/6/30 0030.
 */
@Service
@Slf4j
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    public User getUserById(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Transactional(propagation= Propagation.REQUIRED,rollbackFor={RuntimeException.class, Exception.class})
    public User insertOrUpdate(User user, Long[] roleIds) {
        if( user.getId() != null ){
            User user1 = userMapper.selectByPrimaryKey(user.getId());
            if( user.getPassword() != null && !user1.getPassword().equals(user.getPassword()) ){
                String passwordMd5Hash = new Md5Hash(user.getPassword(), user1.getSalt(),6).toHex();
                user.setPassword(passwordMd5Hash);
            }
            userMapper.updateByPrimaryKeySelective(user);
        }else{
            String salt = GenerateRandomNumber.getCharAndNumr(20);
            user.setSalt(salt);
            String passwordMd5Hash = new Md5Hash(user.getPassword(),salt,6).toHex();
            user.setPassword(passwordMd5Hash);
            userMapper.insert(user);
        }
        List<Long> userIdList = new ArrayList<>();
        userIdList.add(user.getId());
        userRoleMapper.deleteBatchByUserId(userIdList);
        List<UserRole> userRoleList = new ArrayList<>();
        if(!StringUtils.isEmpty(roleIds)){
            for (Long roleId : roleIds){
                userRoleList.add(new UserRole(user.getId(),roleId));
            }
        }
        if( userRoleList.size() > 0 ){
            userRoleMapper.insertUserRoleForeach(userRoleList);
        }
        return user;
    }

    public User selectUserByUserName(String username) {
        User user = userMapper.selectUserByUserName(username);
        return user;
    }

    /**
     * 不使用 PageHelper 做分页是因为一对多查询是
     * @param pageSize
     * @param currentPage
     * @param username
     * @param status
     * @return
     */
    public JsonResult selectByMap(Integer pageSize,Integer currentPage,String username,Integer status) {
        JsonResult jr = new JsonResult();
        /* PageHelper.startPage(currentPage, pageSize);*/
        currentPage = currentPage > 1 ? (currentPage - 1) * pageSize : 0;
        Map<String, Object> map = new HashMap<>();
        map.put("username",username);
        map.put("status",status);
        map.put("pageSize",pageSize);
        map.put("currentPage",currentPage);
        List<User> userList = userMapper.selectByMap(map);
       /* PageInfo<User> userPageInfo = new PageInfo<>(userList);*/
        jr.setData(userList);
        jr.setNumber(userMapper.countUser());
        return jr;
    }

    public void deleteUser(Long id) {
        userMapper.deleteByPrimaryKey(id);
    }

    @Transactional(propagation= Propagation.REQUIRED,rollbackFor={RuntimeException.class, Exception.class})
    public void deleteBatch(String itemIds) {
        String[] roleArray = itemIds.split(",");
        List<Long> userIdList = new ArrayList<>();
        for ( String id : roleArray){
            userIdList.add(Long.parseLong(id));
        }
        userMapper.deleteBatchByUserId(userIdList);
        userRoleMapper.deleteBatchByUserId(userIdList);
    }

    @Transactional(propagation= Propagation.REQUIRED,rollbackFor={RuntimeException.class, Exception.class})
    public void updateStatus(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

}
